package com.clubs.coding.Service.Impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import com.clubs.coding.Service.AppliCationService;

import com.clubs.coding.exception.ImoocMallException;
import com.clubs.coding.exception.ImoocMallExceptionEnum;
import com.clubs.coding.model.Vo.MakeItemNoVo;
import com.clubs.coding.model.Vo.MakeTimeVo;
import com.clubs.coding.model.Vo.MessageVo;
import com.clubs.coding.model.dao.*;
import com.clubs.coding.model.pojo.*;
import com.clubs.coding.model.query.MesgList;
import com.clubs.coding.model.request.DataReq;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class AppliCationServiceImpl implements AppliCationService {
    @Autowired
    ApplicationMapper applicationMapper;
    @Autowired
    MakeTimeMapper makeTimeMapper;
    @Autowired
    LearningMapper learningMapper;
    @Autowired
    AthRecordMapper athRecordMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ClassifyRecordMapper classifyRecordMapper;
    @Override
    //报名
    @Transactional(rollbackFor = Exception.class)
    public void appli(Integer child, String name, String mobile, Integer maketimeId, String openid) throws IOException {
        //对扣费表进行处理
        //新建FIFOCache
        Cache<String,ClassifyRecord> fifoCache = CacheUtil.newFIFOCache(3);
        ClassifyRecord classifyRecord = classifyRecordMapper.selectByPrimaryKey(1);
        fifoCache.put("key1", classifyRecord, DateUnit.SECOND.getMillis() * 3);
        //value1为null
        ClassifyRecord classifyRecord1 = fifoCache.get("key1");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //查是否存在这个项目
        MakeTime makeTime = makeTimeMapper.selectByPrimaryKey(maketimeId);


        if (makeTime == null) {
            throw new ImoocMallException(ImoocMallExceptionEnum.MAKE_ID_NO);
        }
        //检查报名人数
        if (makeTime.getLimitResidue() == 0) {
            throw new ImoocMallException(ImoocMallExceptionEnum.APLI_FULL);
        }
        //对报名的数据进行处理
        List<String> result = Arrays.asList(name.split(","));
        Application application = new Application();
        application.setApplicationTime(new Date());
        application.setMakeTimeId(maketimeId);
        application.setMobile(mobile);
        application.setOpenid(openid);


        //对学习记录表的处理
        Learning learning = new Learning();
        learning.setApplicationId(maketimeId);
        learning.setProjectName(makeTime.getProjectName());
        learning.setSite(makeTime.getSite());
        learning.setTarget(makeTime.getTarget());
        learning.setAboutTime(makeTime.getAboutTime());
        learning.setOpenid(openid);



        //对课时表的操作
        User byOpenid = userMapper.findByOpenid(openid);
        if (byOpenid ==null) {
            throw new ImoocMallException(ImoocMallExceptionEnum.OPENID_NO);
        }
        Integer id = byOpenid.getId();
        AthRecord athRecord = athRecordMapper.selectByUserId(id);
        athRecord.setUpdadeTime(new Date());




        //两个孩子以以上报名的情况
        int insertSelective = 0;
        Integer childs = child;
        if (child >= 2) {

            for (int j = 0; j < result.size(); j++) {

                application.setName(result.get(j));
                insertSelective = applicationMapper.insertSelective(application);
                if (insertSelective == 0) {
                    throw new ImoocMallException(ImoocMallExceptionEnum.APLI_NO);
                }
                if (makeTime.getLimitResidue()>childs) {
                    makeTime.setLimitResidue(makeTime.getLimitResidue() - 1);
                    makeTimeMapper.updateByPrimaryKeySelective(makeTime);
                }else {
                    throw new ImoocMallException(ImoocMallExceptionEnum.APLI_FULL);
                }

                //两个孩子以以上报名的情况对学习记录表的处理
                learning.setChildName(result.get(j));
                int count = learningMapper.insertSelective(learning);
                if (count == 0) {
                    throw new ImoocMallException(ImoocMallExceptionEnum.LEAROMG_NO);
                }
                //课时
                //次卡
                if(athRecord.getRestRecord()!=null){
                    if (athRecord.getRestRecord()>=classifyRecord1.getRestRecord()*childs) {
                        athRecord.setRestRecord(athRecord.getRestRecord()-classifyRecord1.getRestRecord());
                    }else{
                        throw new ImoocMallException(ImoocMallExceptionEnum.RECORD_NO);
                    }
                }
               //充值卡
                if (athRecord.getRefillCard()!=null){
                    if (athRecord.getRefillCard()>=classifyRecord1.getRefillCard()*childs) {
                        athRecord.setRefillCard(athRecord.getRefillCard()-classifyRecord1.getRefillCard());
                    }else{
                        throw new ImoocMallException(ImoocMallExceptionEnum.RECORD_NO);
                    }
                }
                //年卡
                if(athRecord.getYearEndTime()!=null){
                    if(athRecord.getYearEndTime().after((new Date()))){

                    }else{
                        throw new ImoocMallException(ImoocMallExceptionEnum.RECORD_NO);
                    }
                }

                 athRecordMapper.updateByPrimaryKeySelective(athRecord);
                childs--;
            }

        } else {//一个孩子报名的情况
            application.setName(name);

            insertSelective = applicationMapper.insertSelective(application);

            if (insertSelective == 0) {
                throw new ImoocMallException(ImoocMallExceptionEnum.APLI_NO);
            }
            if (makeTime.getLimitResidue()>=1) {
                makeTime.setLimitResidue(makeTime.getLimitResidue() - 1);
                makeTimeMapper.updateByPrimaryKeySelective(makeTime);
            }else {
                throw new ImoocMallException(ImoocMallExceptionEnum.APLI_FULL);
            }

            //一个孩子报名的情况 对学习记录表的生成
            learning.setChildName(name);
            int count = learningMapper.insertSelective(learning);
            if (count == 0) {
                throw new ImoocMallException(ImoocMallExceptionEnum.LEAROMG_NO);
            }
            //课时
            //次卡
            if(athRecord.getRestRecord()!=null){
                if (athRecord.getRestRecord()>=classifyRecord1.getRestRecord()) {
                    athRecord.setRestRecord(athRecord.getRestRecord()-classifyRecord1.getRestRecord());
                }else{
                    throw new ImoocMallException(ImoocMallExceptionEnum.RECORD_NO);
                }
            }
            //充值卡
            if (athRecord.getRefillCard()!=null){
                if (athRecord.getRefillCard()>=classifyRecord1.getRefillCard()) {
                    athRecord.setRefillCard(athRecord.getRefillCard()-classifyRecord1.getRefillCard());
                }else{
                    throw new ImoocMallException(ImoocMallExceptionEnum.RECORD_NO);
                }
            }
            //年卡
            if(athRecord.getYearEndTime()!=null){
                if(athRecord.getYearEndTime().after(new Date())){

                }else{
                    throw new ImoocMallException(ImoocMallExceptionEnum.RECORD_NO);
                }
            }


            athRecordMapper.updateByPrimaryKeySelective(athRecord);
        }


    }

    @Override
    public List<Application> rname(Integer makeTimeId) {//获取该报名的姓名
        List applications = applicationMapper.selectByMakeTimeId(makeTimeId);
        return applications;
    }

    @Override
    public List<MessageVo> selectmesageVO(MesgList mesgList) {
        List<MessageVo> messageVos = applicationMapper.selectmesageVO(mesgList);
        return messageVos;
    }
/**
 * 我的所有报名
 * **/
    @Override
    public PageInfo isAppliAll(String openid, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MakeTimeVo> makeTimeVos = applicationMapper.selectAllBygl(openid);



        PageInfo pageInfo = new PageInfo(makeTimeVos);
        pageInfo.setList(makeTimeVos);
        return pageInfo;
    }

/**
 * 我的今日预约
 * **/
@Override
public List<MakeItemNoVo> myDay(DataReq dataReq){
    List<MakeItemNoVo> makeItemNoVos = applicationMapper.selectMyDay(dataReq);
    return makeItemNoVos;
}

}
